﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Platform;

namespace GameClient
{
    class GatewayAgant
    {
        private bool m_bRunFlag = false;
        private SocketClient m_Socket = new SocketClient();
        private delegate void ProtocalCallBack(byte[] byPackData, int nDataLen);
        private ProtocalCallBack[] m_Callbacks = new ProtocalCallBack[(int)G2C_Protocal.g2c_protocal_count];

        private static GatewayAgant m_GatewayAgentInstace = new GatewayAgant();

        public GatewayAgant()
        {
            // m_Callbacks[(int)G2C_Protocal.g2c_ping_signal] = OnPingSignal;
        }

        public static GatewayAgant GetInstace()
        {
            return m_GatewayAgentInstace;
        }

        public void Setup(string szIP, int nPort)
        {
            m_Socket.Connect(szIP, nPort);
        }

        private void Clear()
        {
            m_Socket.Disconnect();
        }

        public void Run()
        {
            m_bRunFlag = true;
            DoPingSignal();

			// 查看一下效率，如果不行就用异步的 TODO
            ProcessRecvData();
        }

        public void Stop()
        {
            m_bRunFlag = false;
            Clear();
        }

        public bool IsConnected()
        {
            return m_Socket.IsConnected();
        }

        private void ProcessRecvData()
        {
            if (!m_Socket.IsConnected())
                return;

            byte[] byData = m_Socket.Recv();
            if (byData == null)
                return;

            // 在收包的时候与服务器断开连接，需要处理这个异常 TODO
            if (byData[0] >= 0 && byData[0] < (byte)G2C_Protocal.g2c_protocal_count)
                return;

            ProtocalCallBack fn = m_Callbacks[byData[0]];
            if (fn != null)
            {
                fn(byData, byData.Length);
            }
        }

        // 以下是协议处理函数

        public void DoPingSignal()
        {
            C2G_PING_SIGNAL Request = new C2G_PING_SIGNAL();

            Request.nProtocal = (byte)C2G_Protocal.c2g_ping_signal;

            m_Socket.Send(Request);
        }

        public void DohandshakeRequest()
        {
            C2G_HANDSHAKE_REQUEST Request = new C2G_HANDSHAKE_REQUEST();

            Request.nProtocal = (byte)C2G_Protocal.c2g_handshake_request;

            m_Socket.Send(Request);
        }

        public void DoAccountLoginRequest(string szAccount)
        {
            C2G_ACCOUNT_LOGIN_REQUEST Request = new C2G_ACCOUNT_LOGIN_REQUEST();

            Request.nProtocal = (byte)C2G_Protocal.c2g_account_login_request;
            // Request.szAccount = Encoding.ASCII.GetBytes(szAccount, 0, 33);
        }
    }
}
